/**
 * @author ylf
 * @createTime 2014-10-13 下午12:53:51
 */
package mumu.android.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.LinearLayout;
import android.widget.Scroller;

/**
 * @author ylf
 * @createTime 2014-10-13 下午12:53:51
 */
public class MyLinearLayout extends LinearLayout {
	private Scroller mScroller;
	private GestureDetector gDetector;

	public MyLinearLayout(Context context, AttributeSet attrs) {
		this(context);
	}

	public MyLinearLayout(Context ctx) {
		super(ctx);
		mScroller = new Scroller(ctx);
		gDetector = new GestureDetector(ctx, new OnGestureListener() {

			@Override
			public boolean onSingleTapUp(MotionEvent e) {
				return false;
			}

			@Override
			public void onShowPress(MotionEvent e) {

			}

			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
				Log.d("dd", "distanceX=" + distanceX + " distanceY=" + distanceY);
				// 跟随手指移动
				scrollBy((int) distanceX, 0);
				return true;
			}

			@Override
			public void onLongPress(MotionEvent e) {

			}

			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
				return false;
			}

			@Override
			public boolean onDown(MotionEvent e) {
				return false;
			}
		});
	}

	/**
	 * scroler回调
	 */
	@Override
	public void computeScroll() {
		// 如果mScroller没有调用startScroll，这里将会返回false。
		if (mScroller.computeScrollOffset()) {
			Log.d("dd", "mScroller.getCurrX()=" + mScroller.getCurrX());
			scrollTo(mScroller.getCurrX(), 0);
			invalidate();
		}
	}

	/**
	 * 回归初始位置
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		gDetector.onTouchEvent(event);
		if (event.getAction() == MotionEvent.ACTION_UP) {
			int cx = getScrollX();
			mScroller.startScroll(cx, 0, -cx, 0, 500);
			invalidate();
			return false;
		}

		return true;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if (gDetector.onTouchEvent(ev)) {
			return true;
		} else {
			return super.onInterceptTouchEvent(ev);
		}
	}

}